package iot_hmbird

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

type HummingBirdOpenApi struct {
	addr   string
	client *http.Client
	xToken string
}

func NewHummingBirdOpenApi(addr string) *HummingBirdOpenApi {
	client := &http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}
	if !strings.HasPrefix(addr, "http") {
		addr = "http://" + addr
	}

	return &HummingBirdOpenApi{
		addr:   addr,
		client: client,
	}
}

// InvokeDeviceService 调用设备服务
func (api *HummingBirdOpenApi) InvokeDeviceService(params InvokeThingServiceRequest) (InvokeThingServiceResponse, error) {
	var data InvokeThingServiceResponse
	reqBody, err := json.Marshal(params)
	if err != nil {
		return data, err
	}

	req, err := http.NewRequest(http.MethodPost, api.addr+"/v1.0/openapi/invokeThingService", bytes.NewReader(reqBody))
	if err != nil {
		return data, err
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("x-token", api.xToken)
	resp, err := api.client.Do(req)
	if err != nil {
		return data, err
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	var tmp CommonResponse
	if err := json.Unmarshal(body, &tmp); err != nil {
		return data, fmt.Errorf("%s,%s", err, body)
	}
	if !tmp.Success {
		return InvokeThingServiceResponse{CommonResponse: tmp}, nil
	}
	if err := json.Unmarshal(body, &data); err != nil {
		return data, fmt.Errorf("%s,%s", err, body)
	}
	return data, nil
}

func (api *HummingBirdOpenApi) OpenAccessToken(params AuthRequest) (AuthResponse, error) {
	var data AuthResponse
	reqBody, err := json.Marshal(params)
	if err != nil {
		return data, err
	}

	req, err := http.NewRequest(http.MethodPost, api.addr+"/v1.0/openapi/auth/login", bytes.NewReader(reqBody))
	if err != nil {
		return data, err
	}
	req.Header.Add("Content-Type", "application/json")
	resp, err := api.client.Do(req)
	if err != nil {
		return data, err
	}
	defer resp.Body.Close()

	de := json.NewDecoder(resp.Body)
	//de.UseNumber()
	if err := de.Decode(&data); err != nil {
		return data, err
	}

	return data, nil
}

func (api *HummingBirdOpenApi) AddXToken(token string) {
	api.xToken = token
}
